package com.example.miaosha.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置类
 *
 * @Author
 * @Date 2022/1/18 13:32
 */
@Slf4j
@Configuration
@EnableAsync//开启异步调用
public class ThreadExecutorConfig {

    /**
     * 核心线程数
     */
    private int corePoolSize = 10;
    /**
     * 最大线程数
     */
    private int maxPoolSize = 200;
    /**
     * 队列数
     */
    private int queueCapacity = 10;

    @Bean
    public ExecutorService testFxbDrawExecutor() {
        log.info("[线程池启动]");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        log.info("线程数为：{}", corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        log.info("最大连接数为：{}", maxPoolSize);
        // 设置 ThreadPoolExecutor 的 BlockingQueue 的容量
        executor.setQueueCapacity(queueCapacity);
        log.info("阻塞队列长度为：{}", queueCapacity);
        executor.setThreadNamePrefix("seckill-service-");

        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        // 设置要用于ExecutorService的RejectedExecutionHandler。
        // Default是ExecutorService的默认中止策略。
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 执行初始化
        executor.initialize();
        log.info("[线程池启动完成,直接使用ExecutorService注入即可使用]");
        return executor.getThreadPoolExecutor();
    }
}
